home *** CD-ROM | disk | FTP | other *** search
/ Windows Expert / Windows Expert.iso / windownt / tusrc.zip / SRC / PASTE.C < prev    next >
C/C++ Source or Header  |  1993-09-19  |  13KB  |  481 lines

  1. /* paste - merge lines of files
  2.    Copyright (C) 1984 by David M. Ihnat
  3.  
  4.    This program is a total rewrite of the Bell Laboratories Unix(Tm)
  5.    command of the same name, as of System V.  It contains no proprietary
  6.    code, and therefore may be used without violation of any proprietary
  7.    agreements whatsoever.  However, you will notice that the program is
  8.    copyrighted by me.  This is to assure the program does *not* fall
  9.    into the public domain.  Thus, I may specify just what I am now:
  10.    This program may be freely copied and distributed, provided this notice
  11.    remains; it may not be sold for profit without express written consent of
  12.    the author.
  13.    Please note that I recreated the behavior of the Unix(Tm) 'paste' command
  14.    as faithfully as possible, with minor exceptions; however,
  15.    I haven't run a full set of regression tests.  Thus, the user of
  16.    this program accepts full responsibility for any effects or loss;
  17.    in particular, the author is not responsible for any losses,
  18.    explicit or incidental, that may be incurred through use of this program.
  19.  
  20.    I ask that any bugs (and, if possible, fixes) be reported to me when
  21.    possible.  -David Ihnat (312) 784-4544 ignatz@homebru.chi.il.us
  22.  
  23.    The list of valid escape sequences has been expanded over the Unix
  24.    version, to include \b, \f, \r, and \v.
  25.  
  26.    POSIX changes, bug fixes, long-named options, and cleanup
  27.    by David MacKenzie <djm@gnu.ai.mit.edu>.
  28.  
  29.    Options:
  30.    --serial
  31.    -s                Paste one file at a time rather than
  32.                 one line from each file.
  33.    --delimiters=delim-list
  34.    -d delim-list        Consecutively use the characters in
  35.                 DELIM-LIST instead of tab to separate
  36.                 merged lines.  When DELIM-LIST is exhausted,
  37.                 start again at its beginning.
  38.    A FILE of `-' means standard input.
  39.    If no FILEs are given, standard input is used. */
  40.  
  41. #include <stdio.h>
  42. #include "../lib/getopt.h"
  43. #include <sys/types.h>
  44. #include "system.h"
  45. #include "version.h"
  46.  
  47. void error ();
  48. char *xmalloc ();
  49. char *xrealloc ();
  50.  
  51. static char *collapse_escapes ();
  52. static int paste_parallel ();
  53. static int paste_serial ();
  54. static void usage ();
  55.  
  56. /* Indicates that no delimiter should be added in the current position. */
  57. #define EMPTY_DELIM '\0'
  58.  
  59. /* Element marking a file that has reached EOF and been closed. */
  60. #define    CLOSED ((FILE *) -1)
  61.  
  62. /* Element marking end of list of open files. */
  63. #define ENDLIST ((FILE *) -2)
  64.  
  65. /* Name this program was run with. */
  66. char *program_name;
  67.  
  68. /* If nonzero, we have read standard input at some point. */
  69. static int have_read_stdin;
  70.  
  71. /* If nonzero, merge subsequent lines of each file rather than
  72.    corresponding lines from each file in parallel. */
  73. static int serial_merge;
  74.  
  75. /* The delimeters between lines of input files (used cyclically). */
  76. static char *delims;
  77.  
  78. /* A pointer to the character after the end of `delims'. */
  79. static char *delim_end;
  80.  
  81. /* If non-zero, display usage information and exit.  */
  82. static int flag_help;
  83.  
  84. /* If non-zero, print the version on standard error.  */
  85. static int flag_version;
  86.  
  87. static struct option const longopts[] =
  88. {
  89.   {"serial", no_argument, 0, 's'},
  90.   {"delimiters", required_argument, 0, 'd'},
  91.   {"help", no_argument, &flag_help, 1},
  92.   {"version", no_argument, &flag_version, 1},
  93.   {0, 0, 0, 0}
  94. };
  95.  
  96. void
  97. main (argc, argv)
  98.      int argc;
  99.      char **argv;
  100. {
  101.   int optc, exit_status;
  102.   char default_delims[2], zero_delims[3];
  103.  
  104.   program_name = argv[0];
  105.   have_read_stdin = 0;
  106.   serial_merge = 0;
  107.   delims = default_delims;
  108.   strcpy (delims, "\t");
  109.   strcpy (zero_delims, "\\0");
  110.  
  111.   while ((optc = getopt_long (argc, argv, "d:s", longopts, (int *) 0))
  112.      != EOF)
  113.     {
  114.       switch (optc)
  115.     {
  116.     case 0:
  117.       break;
  118.  
  119.     case 'd':
  120.       /* Delimiter character(s). */
  121.       if (optarg[0] == '\0')
  122.         optarg = zero_delims;
  123.       delims = optarg;
  124.       break;
  125.  
  126.     case 's':
  127.       serial_merge++;
  128.       break;
  129.  
  130.     default:
  131.       usage ();
  132.     }
  133.     }
  134.  
  135.   if (flag_version)
  136.     {
  137.       fprintf (stderr, "%s\n", version_string);
  138.       exit (0);
  139.     }
  140.  
  141.   if (flag_help)
  142.     usage ();
  143.  
  144.   if (optind == argc)
  145.     argv[argc++] = "-";
  146.  
  147.   delim_end = collapse_escapes (delims);
  148.  
  149.   if (!serial_merge)
  150.     exit_status = paste_parallel (argc - optind, &argv[optind]);
  151.   else
  152.     exit_status = paste_serial (argc - optind, &argv[optind]);
  153.   if (have_read_stdin && fclose (stdin) == EOF)
  154.     error (1, errno, "-");
  155.   if (ferror (stdout) || fclose (stdout) == EOF)
  156.     error (1, errno, "write error");
  157.   exit (exit_status);
  158. }
  159.  
  160. /* Replace backslash representations of special characters in
  161.    STRPTR with their actual values.
  162.    The set of possible backslash characters has been expanded beyond
  163.    that recognized by the Unix version.
  164.  
  165.    Return a pointer to the character after the new end of STRPTR. */
  166.  
  167. static char *
  168. collapse_escapes (strptr)
  169.      char *strptr;
  170. {
  171.   register char *strout;
  172.  
  173.   strout = strptr;        /* Start at the same place, anyway. */
  174.  
  175.   while (*strptr)
  176.     {
  177.       if (*strptr != '\\')    /* Is it an escape character? */
  178.     *strout++ = *strptr++;    /* No, just transfer it. */
  179.       else
  180.     {
  181.       switch (*++strptr)
  182.         {
  183.         case '0':
  184.           *strout++ = EMPTY_DELIM;
  185.           break;
  186.  
  187.         case 'b':
  188.           *strout++ = '\b';
  189.           break;
  190.  
  191.         case 'f':
  192.           *strout++ = '\f';
  193.           break;
  194.  
  195.         case 'n':
  196.           *strout++ = '\n';
  197.           break;
  198.  
  199.         case 'r':
  200.           *strout++ = '\r';
  201.           break;
  202.  
  203.         case 't':
  204.           *strout++ = '\t';
  205.           break;
  206.  
  207.         case 'v':
  208.           *strout++ = '\v';
  209.           break;
  210.  
  211.         default:
  212.           *strout++ = *strptr;
  213.           break;
  214.         }
  215.       strptr++;
  216.     }
  217.     }
  218.   return strout;
  219. }
  220.  
  221. /* Perform column paste on the NFILES files named in FNAMPTR.
  222.    Return 0 if no errors, 1 if one or more files could not be
  223.    opened or read. */
  224.  
  225. static int
  226. paste_parallel (nfiles, fnamptr)
  227.      int nfiles;
  228.      char **fnamptr;
  229. {
  230.   int errors = 0;        /* 1 if open or read errors occur. */
  231.   /* Number of files for which space is allocated in `delbuf' and `fileptr'.
  232.      Enlarged as necessary. */
  233.   int file_list_size = 12;
  234.   int chr;            /* Input character. */
  235.   int line_length;        /* Number of chars in line. */
  236.   int somedone;            /* 0 if all files empty for this line. */
  237.   /* If all files are just ready to be closed, or will be on this
  238.      round, the string of delimiters must be preserved.
  239.      delbuf[0] through delbuf[file_list_size]
  240.      store the delimiters for closed files. */
  241.   char *delbuf;
  242.   int delims_saved;        /* Number of delims saved in `delbuf'. */
  243.   register char *delimptr;    /* Cycling pointer into `delims'. */
  244.   FILE **fileptr;        /* Streams open to the files to process. */
  245.   int files_open;        /* Number of files still open to process. */
  246.   int i;            /* Loop index. */
  247.   int opened_stdin = 0;        /* Nonzero if any fopen got fd 0. */
  248.  
  249.   delbuf = (char *) xmalloc (file_list_size + 2);
  250.   fileptr = (FILE **) xmalloc ((file_list_size + 1) * sizeof (FILE *));
  251.  
  252.   /* Attempt to open all files.  This could be expanded to an infinite
  253.      number of files, but at the (considerable) expense of remembering
  254.      each file and its current offset, then opening/reading/closing.  */
  255.  
  256.   for (files_open = 0; files_open < nfiles; ++files_open)
  257.     {
  258.       if (files_open == file_list_size - 2)
  259.     {
  260.       file_list_size += 12;
  261.       delbuf = (char *) xrealloc (delbuf, file_list_size + 2);
  262.       fileptr = (FILE **) xrealloc (fileptr, (file_list_size + 1)
  263.                     * sizeof (FILE *));
  264.     }
  265.       if (!strcmp (fnamptr[files_open], "-"))
  266.     {
  267.       have_read_stdin = 1;
  268.       fileptr[files_open] = stdin;
  269.     }
  270.       else
  271.     {
  272.       fileptr[files_open] = fopen (fnamptr[files_open], "r");
  273.       if (fileptr[files_open] == NULL)
  274.         error (1, errno, "%s", fnamptr[files_open]);
  275.       else if (fileno (fileptr[files_open]) == 0)
  276.         opened_stdin = 1;
  277.     }
  278.     }
  279.  
  280.   fileptr[files_open] = ENDLIST;
  281.  
  282.   if (opened_stdin && have_read_stdin)
  283.     error (1, 0, "standard input is closed");
  284.  
  285.   /* Read a line from each file and output it to stdout separated by a
  286.      delimiter, until we go through the loop without successfully
  287.      reading from any of the files. */
  288.  
  289.   while (files_open)
  290.     {
  291.       /* Set up for the next line. */
  292.       somedone = 0;
  293.       delimptr = delims;
  294.       delims_saved = 0;
  295.  
  296.       for (i = 0; fileptr[i] != ENDLIST && files_open; i++)
  297.     {
  298.       line_length = 0;    /* Clear so we can easily detect EOF. */
  299.       if (fileptr[i] != CLOSED)
  300.         {
  301.           chr = getc (fileptr[i]);
  302.           if (chr != EOF && delims_saved)
  303.         {
  304.           fwrite (delbuf, sizeof (char), delims_saved, stdout);
  305.           delims_saved = 0;
  306.         }
  307.  
  308.           while (chr != EOF)
  309.         {
  310.           line_length++;
  311.           if (chr == '\n')
  312.             break;
  313.           putc (chr, stdout);
  314.           chr = getc (fileptr[i]);
  315.         }
  316.         }
  317.  
  318.       if (line_length == 0)
  319.         {
  320.           /* EOF, read error, or closed file.
  321.          If an EOF or error, close the file and mark it in the list. */
  322.           if (fileptr[i] != CLOSED)
  323.         {
  324.           if (ferror (fileptr[i]))
  325.             {
  326.               error (0, errno, "%s", fnamptr[i]);
  327.               errors = 1;
  328.             }
  329.           if (fileptr[i] == stdin)
  330.             clearerr (fileptr[i]); /* Also clear EOF. */
  331.           else if (fclose (fileptr[i]) == EOF)
  332.             {
  333.               error (0, errno, "%s", fnamptr[i]);
  334.               errors = 1;
  335.             }
  336.               
  337.           fileptr[i] = CLOSED;
  338.           files_open--;
  339.         }
  340.  
  341.           if (fileptr[i + 1] == ENDLIST)
  342.         {
  343.           /* End of this output line.
  344.              Is this the end of the whole thing? */
  345.           if (somedone)
  346.             {
  347.               /* No.  Some files were not closed for this line. */
  348.               if (delims_saved)
  349.             {
  350.               fwrite (delbuf, sizeof (char), delims_saved, stdout);
  351.               delims_saved = 0;
  352.             }
  353.               putc ('\n', stdout);
  354.             }
  355.           continue;    /* Next read of files, or exit. */
  356.         }
  357.           else
  358.         {
  359.           /* Closed file; add delimiter to `delbuf'. */
  360.           if (*delimptr != EMPTY_DELIM)
  361.             delbuf[delims_saved++] = *delimptr;
  362.           if (++delimptr == delim_end)
  363.             delimptr = delims;
  364.         }
  365.         }
  366.       else
  367.         {
  368.           /* Some data read. */
  369.           somedone++;
  370.  
  371.           /* Except for last file, replace last newline with delim. */
  372.           if (fileptr[i + 1] != ENDLIST)
  373.         {
  374.           if (chr != '\n')
  375.             putc (chr, stdout);
  376.           if (*delimptr != EMPTY_DELIM)
  377.             putc (*delimptr, stdout);
  378.           if (++delimptr == delim_end)
  379.             delimptr = delims;
  380.         }
  381.           else
  382.         putc (chr, stdout);
  383.         }
  384.     }
  385.     }
  386.   return errors;
  387. }
  388.  
  389. /* Perform serial paste on the NFILES files named in FNAMPTR.
  390.    Return 0 if no errors, 1 if one or more files could not be
  391.    opened or read. */
  392.  
  393. static int
  394. paste_serial (nfiles, fnamptr)
  395.      int nfiles;
  396.      char **fnamptr;
  397. {
  398.   int errors = 0;        /* 1 if open or read errors occur. */
  399.   register int charnew, charold; /* Current and previous char read. */
  400.   register char *delimptr;    /* Current delimiter char. */
  401.   register FILE *fileptr;    /* Open for reading current file. */
  402.  
  403.   for (; nfiles; nfiles--, fnamptr++)
  404.     {
  405.       if (!strcmp (*fnamptr, "-"))
  406.     {
  407.       have_read_stdin = 1;
  408.       fileptr = stdin;
  409.     }
  410.       else
  411.     {
  412.       fileptr = fopen (*fnamptr, "r");
  413.       if (fileptr == NULL)
  414.         {
  415.           error (0, errno, "%s", *fnamptr);
  416.           errors = 1;
  417.           continue;
  418.         }
  419.     }
  420.  
  421.       delimptr = delims;    /* Set up for delimiter string. */
  422.  
  423.       charold = getc (fileptr);
  424.       if (charold != EOF)
  425.     {
  426.       /* `charold' is set up.  Hit it!
  427.          Keep reading characters, stashing them in `charnew';
  428.          output `charold', converting to the appropriate delimiter
  429.          character if needed.  After the EOF, output `charold'
  430.          if it's a newline; otherwise, output it and then a newline. */
  431.  
  432.       while ((charnew = getc (fileptr)) != EOF)
  433.         {
  434.           /* Process the old character. */
  435.           if (charold == '\n')
  436.         {
  437.           if (*delimptr != EMPTY_DELIM)
  438.             putc (*delimptr, stdout);
  439.  
  440.           if (++delimptr == delim_end)
  441.             delimptr = delims;
  442.         }
  443.           else
  444.         putc (charold, stdout);
  445.  
  446.           charold = charnew;
  447.         }
  448.  
  449.       /* Hit EOF.  Process that last character. */
  450.       putc (charold, stdout);
  451.     }
  452.  
  453.       if (charold != '\n')
  454.     putc ('\n', stdout);
  455.  
  456.       if (ferror (fileptr))
  457.     {
  458.       error (0, errno, "%s", *fnamptr);
  459.       errors = 1;
  460.     }
  461.       if (fileptr == stdin)
  462.     clearerr (fileptr);    /* Also clear EOF. */
  463.       else if (fclose (fileptr) == EOF)
  464.     {
  465.       error (0, errno, "%s", *fnamptr);
  466.       errors = 1;
  467.     }
  468.     }
  469.   return errors;
  470. }
  471.  
  472. static void
  473. usage ()
  474. {
  475.   fprintf (stderr, "\
  476. Usage: %s [-s] [-d delim-list] [--serial] [--delimiters=delim-list]\n\
  477.        [--help] [--version] [file...]\n",
  478.        program_name);
  479.   exit (1);
  480. }
  481.